package com.dcivision.framework.taglib.channel;

import java.sql.Connection;
import java.sql.SQLException;

import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;

/**
 * Thread context for handling pageContext from Ajax request
 * 
 * @author henry.chan
 *
 */
public class AjaxThreadContext extends ThreadLocal {

  protected synchronized Object initialValue() {
    return new AjaxPageContext();
  }
  
  /**
   * Get Ajax page context
   * 
   * @return The thread localized Ajax page context
   */
  public AjaxPageContext getPageContext() {
    return ((AjaxPageContext) get());
  }

  public Connection getConnnection() throws Exception{
    Connection conn = (Connection)getRequestAttribute(GlobalConstant.DB_KEY);
    if(conn==null){
      conn = DataSourceFactory.getConnection();
      this.setRequestAttribute(GlobalConstant.DB_KEY, conn);
    }
    return conn;
  }
  
  public void closeConnection(){
    Connection conn = (Connection)getRequestAttribute(GlobalConstant.DB_KEY);
    if(conn!=null){
      try {
        conn.close();
      } catch (SQLException e) {
        
      }finally{
        conn = null;
      }
    }
  }
  
  public SessionContainer getSessionContainer(){
    SessionContainer ctx = (SessionContainer)getSessionAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    if (ctx==null) {
      ctx = new SessionContainer();
      setSessionAttribute(GlobalConstant.SESSION_CONTAINER_KEY, ctx);
    }
    return(ctx);
  }
  
  /**
   * set request attribute
   * @param key
   * @return
   */
  public Object getRequestAttribute(String key){
    return this.getPageContext().getRequest().getAttribute(key);
  }
  
  public void setRequestAttribute(String key,Object obj){
    this.getPageContext().getRequest().setAttribute(key,obj);
  }
  
  /**
   * set session attribute
   * @param key
   * @return
   */
  public Object getSessionAttribute(String key){
    return this.getPageContext().getSession().getAttribute(key);
  }
  
  public void setSessionAttribute(String key,Object obj){
     this.getPageContext().getSession().setAttribute(key,obj);
  }
  
}
